package com.ling.feign.plus.advice;

import com.ling.common.Result;
import com.ling.common.ResultCode;
import com.ling.common.exception.BaseBusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Order(Ordered.HIGHEST_PRECEDENCE)
@Configuration
@RestControllerAdvice
public class GlobalServerExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalServerExceptionHandler.class);

    /**
     * 封装业务异常
     */
    @ExceptionHandler(value = BaseBusinessException.class)
    public Result<?> handleBusinessException(BaseBusinessException ex,
                                             HttpServletResponse response) {
        log.error("BaseException", ex);
        return Result.error(ex.getCode(), ex.getMsg());
    }

    /**
     * 参数校验的异常
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result<?> handleValidException(MethodArgumentNotValidException ex) {
        String errorMsg;
        List<ObjectError> errors = ex.getBindingResult().getAllErrors();
        if (errors.size() > 0) {
            errorMsg = errors.get(0).getDefaultMessage();
        } else {
            errorMsg = ResultCode.PARAM_ERROR.getMsg();
        }
        log.error("MethodArgumentNotValidException", ex);
        return Result.error(
                ResultCode.PARAM_ERROR,
                errorMsg
        );
    }

    /**
     * 其他非业务异常
     */
    @ExceptionHandler(value = Exception.class)
    public Result<?> handleException(HttpServletRequest request, Exception ex) {
        log.error("Exception", ex);
        return Result.error();
    }
}
